package cn.ld.fj.web.food;

import cn.ld.fj.entity.Food;
import cn.ld.fj.entity.FoodTaste;
import cn.ld.fj.entity.FoodType;
import cn.ld.fj.pojo.FoodTypePojo;
import cn.ld.fj.service.food.FoodManager;
import cn.ld.fj.service.food.FoodTasteManager;
import cn.ld.fj.service.food.FoodTypeManager;
import cn.ld.fj.service.log.OperationLogManager;
import cn.ld.fj.util.Config;
import cn.ld.fj.util.DateUtil;
import cn.ld.fj.util.DwzUtil;
import cn.ld.fj.util.RandomCodeUtil;
import cn.ld.fj.web.JsonActionSupport;
import com.google.common.collect.Lists;
import net.esoar.modules.orm.Page;
import net.esoar.modules.orm.PropertyFilter;
import net.esoar.modules.utils.web.struts2.Struts2Utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 用户管理Action.
 * <p/>
 * 使用Struts2 convention-plugin annotation定义Action参数. 演示带分页的管理界面.
 *
 * @author fly
 */
// 定义URL映射对应/account/user.action
@Namespace("/food")
// 定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results({@Result(name = JsonActionSupport.RELOAD, location = "food.action", type = "redirect")})
public class FoodAction extends JsonActionSupport<Food> {

    private final Logger logger = LoggerFactory.getLogger(FoodAction.class);


    @Autowired
    private FoodManager foodManager;
    @Autowired
    private FoodTasteManager foodTasteManager;
    @Autowired
    private OperationLogManager operationLogManager;

    @Autowired
    private FoodTypeManager foodTypeManager;

    private Long id;
    private Food entity;
    private Page<Food> page = new Page<Food>(10);// 每页5条记录


    private File foodImage;
    private String foodImageFileName;

    private List<FoodTaste> foodTasteList = Lists.newArrayList();


    private List<String> foodTasteNames = Lists.newArrayList();

    public List<String> getFoodTasteNames() {
        return foodTasteNames;
    }


    private List<FoodTypePojo> foodTypePojos = Lists.newArrayList();

    public List<FoodTypePojo> getFoodTypePojos() {
        return foodTypePojos;
    }

    public void setFoodTypePojos(List<FoodTypePojo> foodTypePojos) {
        this.foodTypePojos = foodTypePojos;
    }

    public void setFoodTasteNames(List<String> foodTasteNames) {
        this.foodTasteNames = foodTasteNames;
    }

    public List<FoodTaste> getFoodTasteList() {
        return foodTasteList;
    }

    public void setFoodTasteList(List<FoodTaste> foodTasteList) {
        this.foodTasteList = foodTasteList;
    }

    public File getFoodImage() {
        return foodImage;
    }

    public void setFoodImage(File foodImage) {
        this.foodImage = foodImage;
    }

    public String getFoodImageFileName() {
        return foodImageFileName;
    }

    public void setFoodImageFileName(String foodImageFileName) {
        this.foodImageFileName = foodImageFileName;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Food getModel() {
        return entity;
    }


    public Long getId() {
        return id;
    }

    public Food getEntity() {
        return entity;
    }

    public void setEntity(Food entity) {
        this.entity = entity;
    }

    public Page<Food> getPage() {
        return page;
    }

    public void setPage(Page<Food> page) {
        this.page = page;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = foodManager.getOne(id);
        } else {
            entity = new Food();
        }
    }

    // -- CRUD Action 函数 --//
    @Override
    public String list() throws Exception {
        List<PropertyFilter> filters = PropertyFilter
                .buildFromHttpRequest(Struts2Utils.getRequest());
        // 设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }

        page = foodManager.getPage(page, filters);

        return SUCCESS;
    }

    @Override
    public String input() throws Exception {
        foodTasteList = foodTasteManager.getAll();

        String foodTasteStr = entity.getFoodTastes();
        if (StringUtils.isNotBlank(foodTasteStr)) {

            String[] ss = foodTasteStr.split(",");
            for (String s : ss) {
                foodTasteNames.add(s);
            }
        }


        List<FoodType> foodTypes = foodTypeManager.getFirstLevel();
        if (CollectionUtils.isNotEmpty(foodTypes)) {
            for (FoodType foodType : foodTypes) {
                FoodTypePojo foodTypePojo = new FoodTypePojo();
                foodTypePojo.setId(foodType.getId());
                foodTypePojo.setName(foodType.getName());

                List<FoodType> seconds = foodTypeManager.getSecondFoodTypes(foodType.getId());
                if (CollectionUtils.isNotEmpty(seconds)) {
                    for (FoodType secondFoodType : seconds) {
                        FoodTypePojo secondPojo = new FoodTypePojo();
                        BeanUtils.copyProperties(secondFoodType, secondPojo);

                        List<FoodType> thirds = foodTypeManager.getSecondFoodTypes(secondFoodType.getId());
                        if (CollectionUtils.isNotEmpty(thirds)) {
                            for (FoodType thirdFoodType : thirds) {
                                FoodTypePojo thirdPojo = new FoodTypePojo();
                                BeanUtils.copyProperties(thirdFoodType, thirdPojo);
                                secondPojo.getFoodTypePojoList().add(thirdPojo);
                            }
                        }
                        foodTypePojo.getFoodTypePojoList().add(secondPojo);

                    }
                }
                foodTypePojos.add(foodTypePojo);
            }
        }


        return INPUT;
    }

    @Override
    public void save() throws Exception {


        if (StringUtils.isNotBlank(foodImageFileName)) {
            String tineStr = DateUtil.getTimeStamp() + RandomCodeUtil.generateNumCode(6);
            // 保存地址url
            String url = Config.save_url;
            // 上传动作

            String suffix = foodImageFileName.substring(foodImageFileName.lastIndexOf("."));


            String accessUrl = Config.access_url + tineStr + suffix;

            url = url + tineStr + suffix;

            try {
                FileUtils.copyFile(foodImage, new File(url));
            } catch (IOException e) {
                logger.info("文件地址有误,请修改地址");
            }
            entity.setImage(accessUrl);
        }

        entity.setFoodTastes(createNames(foodTasteNames));

        foodManager.save(entity);

        operationLogManager.saveLog("增加/修改菜品信息");

        Struts2Utils.renderHtml(DwzUtil.getCloseCurrentReturn("w_food",
                "操作成功"));
    }

    private String createNames(List<String> foodTasteNames) {
        StringBuffer stringBuffer = new StringBuffer();
        String result = null;
        if (CollectionUtils.isNotEmpty(foodTasteNames)) {
            for (String name : foodTasteNames) {
                stringBuffer.append(name).append(",");
            }
            result = stringBuffer.toString();
            if (result.lastIndexOf(",") > 0) {
                result = result.substring(0, result.lastIndexOf(","));
            }
        }
        return result;
    }


    @Override
    public void delete() throws Exception {


        try {
            foodManager.delete(id);
            operationLogManager.saveLog("删除菜品信息");
        } catch (Exception e) {
            return;
        }

        Struts2Utils.renderHtml(DwzUtil.getNavtabReturn("w_food",
                "操作成功"));
    }


}
